<template>
  <view>
    <view class="search">
      <uni-search-bar v-model="kw" placeholder="请输入搜索的内容" :radius="100" @input="input" cancelButton="none" />
    </view>

    <!-- 搜索建议列表 -->
    <view class="sugg-list" v-if="searchResults.length !== 0">
      <view class="sugg-item" v-for="(item,index) in searchResults" :key="index" @click="gotoDetail(item)">
        <uni-icons type="search" size="16"></uni-icons>
        <view class="goods-name">{{item.goods_name}}</view>
        <uni-icons type="right" size="16"></uni-icons>
      </view>
    </view>
    <!-- 搜索历史 -->
    <view class="history-box" v-else>
      <!-- 标题区域 -->
      <view class="history-title">
        <text>历史搜索</text>
        <uni-icons type="trash" size="18" @click="clean"></uni-icons>
      </view>
      <!-- 列表区域 -->
      <view class="history-list">
        <uni-tag :text="item" size="normal" v-for="(item,index) in historyies" :key="index"
          custom-style="background-color: #f7f8fd; border-color: #f7f8fd; color:#000000;" @click="gotoGoodsList(item)">
        </uni-tag>
      </view>
    </view>
    <uni-popup ref="alertDialog">
      <uni-popup-dialog class="dialog"  cancelText="取消" confirmText="确定" title="清空" content="您确定要清空历史记录吗？"
        @confirm="dialogConfirm" @close="dialogClose"></uni-popup-dialog>
    </uni-popup>
    
  </view>
</template>

<script>
import icons from '../../uni_modules/uni-icons/components/uni-icons/icons';
  export default {
    data() {
      return {
        //延时器id
        timer: null,
        // 搜搜关键词
        kw: '',
        // 搜索结果列表
        searchResults: [],
        // 搜索关键词历史记录
        historyList: [],
        // 隐藏显示dialog
        dialog: false
      };
    },
    onLoad() {
      this.historyList = JSON.parse(uni.getStorageSync('kw') || '[]')
    },
    // 解决关键词顺序问题
    computed: {
      historyies() {
        return [...this.historyList].reverse()
      }
    },
    methods: {
      // input输入事件函数
      input(e) {
        // 清除定时器
        clearTimeout(this.timer)
        // 重新启动定时器并赋值
        this.timer = setTimeout(() => {
          this.kw = e
          this.getSearchList()
        }, 500)
      },
      async getSearchList() {
        if (this.kw === '') {
          this.searchResults = []
          return
        }
        const {
          data: res
        } = await uni.$http.get('/api/public/v1/goods/qsearch', {
          query: this.kw
        })
        if (res.meta.status !== 200) return uni.$showMsg()
        this.searchResults = res.message
        // 调用保存历史记录函数
        this.saveSearchHistory()
      },
      // 保存历史记录
      saveSearchHistory() {
        const set = new Set(this.historyList)
        set.delete(this.kw)
        set.add(this.kw)
        this.historyList = Array.from(set)

        // 对搜索历史数据，进行持久化存储
        uni.setStorageSync('kw', JSON.stringify(this.historyList))
      },
      // 清空历史记录
      clean() {
        if(this.historyies.length === 0){
          this.$refs.alertDialog.close()
        }else{
          this.$refs.alertDialog.open()
        }
      },
      // 对话框确定按钮
      dialogConfirm() {
        this.$refs.alertDialog.close()
        this.historyList = [],
        uni.removeStorageSync('kw')
        setTimeout(()=>{
          uni.$showMsg('清空成功',2000,'success')
        },50)
      },
      // 对话框取消按钮
      dialogClose() {
        this.$refs.alertDialog.close()
      },
      // 点击搜索历史跳转到商品列表页面
      gotoGoodsList(e) {
        // this.kw = e
          uni.navigateTo({
            url:'/subpkg/goods_list/goods_list?query=' + e 
          })
      },
      // 点击搜索item项跳转到商品详情页
      gotoDetail(item) {
        uni.navigateTo({
          url: '/subpkg/goods_detail/goods_detail?goods_id=' + item.goods_id
        })
      }
    }
  }
</script>

<style lang="scss">
  .search {
    position: sticky;
    top: 0;
    z-index: 9999;
  }

  .sugg-list {
    padding: 0 5px;

    .sugg-item {
      display: flex;
      align-items: center;
      justify-content: space-between;
      font-size: 13px;
      padding: 13px 0;
      border-bottom: 1px solid #efefef;

      .goods-name {
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
      }
    }
  }

  .history-box {
    padding: 0 10px;

    .history-title {
      display: flex;
      justify-content: space-between;
      height: 40px;
      align-items: center;
      font-size: 13px;
      border-bottom: 1px solid #efefef;
    }

    .history-list {
      display: flex;
      flex-wrap: wrap;
      margin-top: 10px;

      .uni-tag {
        margin-left: 5px;
        background-color: #f7f8fd;
      }
    }
  }
  .dialog{
    display: flex;
    justify-content: center;
  }
</style>
